/* main.js 项目主入口注入实例 */
// import mqttTool from './lib/this.js'
// Vue.prototype.$mqttTool = mqttTool

/* 使用范例见 /pages/index/index.vue */
// mqtt协议：H5使用ws/wss APP-PLUS使用wx/wxs

//import * as mqtt from 'mqtt/dist/mqtt.min'

//import * as mqttClient from './mqtt-v3.min.js'

//import * as mqtt from "./mqtt-v3.js";

// #ifdef MP-WEIXIN
	import * as _ from './mqtt-v4.1.0.min.js'
	let mqtt = require('./mqtt-v4.1.0.min.js')
	console.log('AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA-WEIXIN')
// #endif
 
// #ifndef MP-WEIXIN
	import * as mqtt from 'mqtt/dist/mqtt.min'
	console.log('AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA-N-WEIXIN')
// #endif

  
console.log(mqtt)



class Mqtt {
	client = null

	connect(params) {
		let client = mqtt.connect(params.url, params);
		this.client = client
		console.log(client)
		console.log('ppppppppppppppppppp')
		return this;
	}

	end() { 
		return new Promise((resolve, reject) => {
			if (this.client == null) {
				resolve('未连接')
				console.log('App_text' + ":end 未连接")
				return;
			}
			this.client.end()
			this.client = null
			resolve('连接终止')
		})
	}

	reconnect() {
		return new Promise((resolve, reject) => {
			if (this.client == null) {
				resolve('未连接')
				console.log('App_text' + ":reconnect 未连接")
				return;
			}
			this.client.reconnect()
		})
	}

	subscribe(params) {
		return new Promise((resolve, reject) => {
			if (this.client == null) {
				resolve('未连接')
				console.log('App_text' + ":unconnect 未连接")
				return;
			}
			this.client.subscribe(params.topic, {
				qos: params.qos
			}, function(err, res) {
				console.log(err, res)
				if (!err && res.length > 0) {
					resolve('订阅成功')
					console.log('App_text' + ":subscribe success 订阅成功")
				} else {
					resolve('订阅失败')
					console.log('App_text' + ":subscribe failed 订阅失败")
					return;
				}
			})
		})
	}

	unsubscribe(params) {
		return new Promise((resolve, reject) => {
			if (this.client == null) {
				resolve('未连接')
				console.log('App_text' + ":unconnect 未连接")
				return;
			}
			this.client.unsubscribe(params.topic, function(err) {
				if (!err) {
					resolve('取消订阅成功')
					console.log('App_text' + ":unsubscribe success 取消订阅成功")
				} else {
					resolve('取消订阅失败')
					console.log('App_text' + ":unsubscribe failed 取消订阅失败")
					return;
				}
			})
		})
	}

	publish(params) {
		return new Promise((resolve, reject) => {
			if (this.client == null) {
				resolve('未连接')
				console.log('App_text' + ":unconnect 未连接")
				return;
			}
			this.client.publish(params.topic, params.message,params.options, function(err) {
				if (!err) {
					resolve(params.topic + '-' + params.message + '-发送成功')
					console.log('App_text' + ":publish success 发送成功")
				} else {
					resolve(params.topic + '-' + params.message + '-发送失败')
					console.log('App_text' + ":publish failed 发送失败")
					return;
				}
			})
		})
	}
}
export default Mqtt